package com.bjpowernode.boss.mvc.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjpowernode.boss.client.RedisClient;
import com.bjpowernode.boss.client.email.EmailEntity;
import com.bjpowernode.boss.constant.SystemConstant;
import com.bjpowernode.boss.enums.RespInfo;
import com.bjpowernode.boss.events.model.SendEmailEvent;
import com.bjpowernode.boss.exception.PowerException;
import com.bjpowernode.boss.mvc.models.query.UserConfigQuery;
import com.bjpowernode.boss.mvc.service.UserPaymentConfigService;
import com.bjpowernode.boss.persist.domain.UserInfo;
import com.bjpowernode.boss.persist.domain.UserPayConfig;
import com.bjpowernode.boss.persist.domain.UserPayInfo;
import com.bjpowernode.boss.persist.mapper.UserInfoMapper;
import com.bjpowernode.boss.persist.mapper.UserPayConfigMapper;
import com.bjpowernode.boss.persist.mapper.UserPayInfoMapper;
import com.bjpowernode.boss.utils.IdUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserPaymentConfigServiceImpl implements UserPaymentConfigService {

    @Value("${spring.mail.username}")
    private String fromMail="";

    @Resource
    private ApplicationEventPublisher publisher;

    @Resource
    private UserPayConfigMapper userPayConfigMapper;

    @Resource
    private UserPayInfoMapper userPayInfoMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private RedisClient redisClient;

    @Override
    public Page<UserPayConfig> loadUserPayProductPage(int pageNo) {

        return userPayConfigMapper.selectPage(Page.of(pageNo, SystemConstant.PAGE_SIZE),
                new QueryWrapper<UserPayConfig>().orderByAsc("shop_name"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProduct(UserConfigQuery userConfigQuery) {

        Long count = userPayConfigMapper.selectCount(new QueryWrapper<UserPayConfig>()
                .eq("user_no", userConfigQuery.getUserNo())
                .eq("pay_product_code", userConfigQuery.getProductCode()));
        if (count > 0) {
            throw new PowerException(RespInfo.USER_PRODUCT_EXIST_ERROR);
        }
        UserPayConfig userPayConfig = new UserPayConfig();
        //添加用户产品
        insertUserPayConfig(userConfigQuery, userPayConfig);

        StringBuilder payWayCodes = new StringBuilder("");

        //添加用户产品配置
        //配置快钱
        UserConfigQuery.KqConfig kqConfig = userConfigQuery.getKqConfig();
        if (kqConfig != null && StrUtil.isNotBlank(kqConfig.getMerchId())
                && StrUtil.isNotBlank(kqConfig.getPublicFile())
                && StrUtil.isNotBlank(kqConfig.getQueryKey())
                && StrUtil.isNotBlank(kqConfig.getPrivateFile())) {

            insertPayInfo(userConfigQuery, "KUAIQIAN", "快钱",
                    JSONUtil.toJsonStr(kqConfig), "快钱的参数配置");
            payWayCodes.append("快钱（KUAIQIAN）").append(";");
        }

        //配置微信
        UserConfigQuery.WxConfig wxConfig = userConfigQuery.getWxConfig();
        if (wxConfig != null && StrUtil.isNotBlank(wxConfig.getMerchId()) && StrUtil.isNotBlank(wxConfig.getAppId())) {
            insertPayInfo(userConfigQuery, "WEIXIN", "微信",
                    JSONUtil.toJsonStr(wxConfig), "微信的参数配置");

            payWayCodes.append("微信（WEIXIN）").append(";");
        }

        //将用户产品配置保存到Redis
        saveConfig(userPayConfig, kqConfig, wxConfig);

        //将配置信息发送给商户
        //sendEmail(userPayConfig, payWayCodes.toString());

    }

    //删除用户产品配置
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserProductConfig(String userNo, String productCode) {
        if (StrUtil.isBlank(userNo) || StrUtil.isBlank(productCode)) {
            throw new PowerException(RespInfo.REQUEST_PARAM_ERROR);
        }

        int count = userPayConfigMapper.delete(new UpdateWrapper<UserPayConfig>()
                                                     .eq("user_no", userNo)
                                                     .eq("pay_product_code", productCode));
        if (count <= 0) {
            throw new PowerException(RespInfo.USER_PRODUCT_NOT_EXIST_ERROR);
        }
        userPayInfoMapper.delete(new UpdateWrapper<UserPayInfo>()
                                 .eq("user_no", userNo)
                                 .eq("pay_product_code", productCode));

        redisClient.deleteHashAll(userNo + "#" + productCode);
    }

    private void saveConfig(UserPayConfig userPayConfig, UserConfigQuery.KqConfig kqConfig, UserConfigQuery.WxConfig wxConfig) {

        String key = userPayConfig.getUserNo() + "#" + userPayConfig.getPayProductCode();

        Map<String, String> map = new HashMap<>();
        map.put("productCode",userPayConfig.getPayProductCode());
        map.put("productName",userPayConfig.getPayProductName());
        map.put("appKey",userPayConfig.getAppKey());
        map.put("appSecret",userPayConfig.getAppSecret());
        map.put("KUAIQIAN", JSONUtil.toJsonStr(kqConfig));
        map.put("WEIXIN",JSONUtil.toJsonStr(wxConfig));
        map.put("shopName",userPayConfig.getShopName());
        map.put("userNo",userPayConfig.getUserNo());

        redisClient.setHashAll(key, map, 0, null);


    }

    //发送给商家通知邮件
    private void sendEmail(UserPayConfig payConfig,String payWayCodes) {
        //将userNo， appkey ， appSecret ,  productCode ，支付方式编码 ， shopName , 发给商家
        StringBuilder mailText = new StringBuilder("");
        mailText.append("商户号：").append(payConfig.getUserNo()).append(";")
                .append("商铺名称：").append(payConfig.getShopName()).append(";")
                .append("appKey：").append(payConfig.getAppKey()).append(";")
                .append("appSecret：").append(payConfig.getAppSecret()).append(";")
                .append("支付产品代码：").append(payConfig.getPayProductCode()).append(";")
                .append("支付方式代码：").append(payWayCodes).append(";");

        //邮件属性
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_no", payConfig.getUserNo()));

        //触发发送邮件的事件
        EmailEntity mailProperties = new EmailEntity();
        mailProperties.setFrom(fromMail);
        mailProperties.setTo(new String[]{userInfo.getUserEmail()});
        mailProperties.setSubject("商户支付配置邮件");
        mailProperties.setText(mailText.toString());
        publisher.publishEvent(new SendEmailEvent(this,mailProperties));
    }

    private void insertPayInfo(UserConfigQuery userConfigQuery, String payWayCode,
                               String payWayName, String payConfig, String remark) {
        UserPayInfo payInfo = new UserPayInfo();
        payInfo.setId(IdUtil.uuid());
        payInfo.setPayProductCode(userConfigQuery.getProductCode());
        payInfo.setUserNo(userConfigQuery.getUserNo());
        payInfo.setShopName(userConfigQuery.getShopName());
        payInfo.setPayWayCode(payWayCode);
        payInfo.setPayWayName(payWayName);
        payInfo.setPayConfig(payConfig);
        payInfo.setRemark(remark);
        payInfo.setEditTime(new Date());
        payInfo.setStatus("ENABLE");
        userPayInfoMapper.insert(payInfo);
    }

    private void insertUserPayConfig(UserConfigQuery userConfigQuery, UserPayConfig userPayConfig) {
        userPayConfig.setId(IdUtil.uuid());
        userPayConfig.setUserNo(userConfigQuery.getUserNo());
        userPayConfig.setShopName(userConfigQuery.getShopName());
        userPayConfig.setPayProductCode(userConfigQuery.getProductCode());
        userPayConfig.setPayProductName(userConfigQuery.getProductName());
        userPayConfig.setRiskDay(userConfigQuery.getRiskDay());
        userPayConfig.setAppKey(IdUtil.uuid());
        userPayConfig.setAppSecret(IdUtil.uuid());
        userPayConfig.setMerchantServerIp(userConfigQuery.getIpList());
        userPayConfig.setAutoSett(userConfigQuery.getAutoSett());
        userPayConfig.setRemark("创建用户产品配置");
        userPayConfig.setEditTime(new Date());
        userPayConfig.setStatus("ENABLE");
        userPayConfigMapper.insert(userPayConfig);
    }


}
